/*
 * @Description: 
 * @Author: HYH
 * @LastEditors: HYH
 * @LastEditTime: 2023-03-29 10:06:50
 */

import { useNavigate } from 'react-router-dom';
import { reduxActions, useAppDispatch, useAppSelector } from '@/store';
import { Card, Checkbox, Form, Button, Input } from 'antd';
import { useEffect, useRef, useState } from 'react';
import type { FormInstance } from 'antd/es/form';

type ILoginResData = {
  userId: string
  token: string
}

export default () => {
  const [loading, setLoading] = useState(true)
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const formRef = useRef<FormInstance>(null)
  const useDispatch = useAppDispatch()
  const onFinish = (form: any) => {
    http.post<ILoginResData>('/login', form,).then(res => {
      console.log(`res ==>`, res);
      const { userId, token } = res.data
      useDispatch(reduxActions.setToken(token))
      useDispatch(reduxActions.setUserId(userId))
      navigate('/home', { replace: true })
    })
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };


  const onFill = () => {
    formRef.current?.setFieldsValue({ email: '772269729@qq.com', password: '990618' });
  }

  useEffect(() => {
    setTimeout(() => {
      setLoading(false)
    }, 500)
  }, [])



  return (
    <div style={{
      display: 'flex',
      alignItems: "center",
      justifyContent: "center",
      width: '100%',
      height: '100%'
    }}>
      <Card
        style={{ width: 420, }} title='登录' loading={loading}>
        <Form
          ref={formRef}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="email"
            name="email"
            rules={[{ required: true, message: '请输入邮箱!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="Password"
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 8, span: 16 }}>
            <Checkbox>Remember me</Checkbox>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
            <Button htmlType="reset" style={{ margin: '0 5px' }} >
              重置
            </Button>
            <Button htmlType="button" onClick={onFill}>
              自动填充
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
